<template>
  <v-ace-editor
    v-model:value="content"
    :theme="theme"
    :lang="lang"
    style="height: 70vh"
    :readonly="isReadonly"
    @init="onEditorInit"
    @change="handleChange"
    ref="editorRef"
  />
</template>
<script setup lang="ts">
  import { ref, onMounted, unref, watch, nextTick } from 'vue';
  import { VAceEditor } from 'vue3-ace-editor';
  import './ace.config';
  const props = defineProps({
    isReadonly: {
      type: Boolean,
      default: false,
    },
    modelValue: {
      type: String,
      default: '',
    },
    lang: {
      type: String,
      default: 'java',
    },
  });
  const edits = defineEmits(['update:modelValue']);
  const editorRef = ref<Nullable<HTMLElement>>(null);

  onMounted(() => {});

  const content = ref('');
  watch(
    () => props.modelValue,
    async () => {
      await nextTick();
      content.value = props.modelValue;
      console.log('content.value', content.value);
      console.log('editorRef', unref(editorRef));
    },
    {
      immediate: true,
      // deep: true,
    },
  );
  watch(
    () => props.isReadonly,
    async () => {
      await nextTick();
      console.log('isReadonly', props.isReadonly);
      editorRef.value?.getAceInstance()?.setReadOnly(props.isReadonly);
    },
    {
      immediate: true,
      // deep: true,
    },
  );
  // watchEffect(() => {
  //   content.value = props.value;
  // });
  const theme = ref('chrome');
  const setTheme = (value) => {
    console.log('theme', value);
    theme.value = value;
  };

  //插入值
  const insertScript = (script) => {
    console.log('editorRef', unref(editorRef));
    console.log('script', script);
    if (unref(editorRef)) {
      unref(editorRef)?._editor?.insert(script);
      unref(editorRef)?._editor?.focus();
    }
  };

  const handleChange = (val) => {
    console.log(val, content.value);
    edits('update:modelValue', content.value);
  };

  const onEditorInit = (editor) => {
    editor.session.setMode('ace/mode/' + props.lang);
  };

  defineExpose({
    setTheme,
    insertScript,
  });
</script>
